/*
 * Copyright (c) 2018 maoyan.com
 * All rights reserved.
 *
 */
package com.darren.euc.job;

import com.alibaba.fastjson.JSONArray;
import com.darren.euc.entity.BookTimeRange;
import com.darren.euc.entity.MeetingroomOrder;
import com.darren.euc.repository.MeetingroomOrderRepository;
import com.darren.euc.util.DateUtil;
import com.google.common.collect.Lists;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

import static com.darren.euc.util.GenegateDomainUtil.isAvaliable;

/**
 * 在这里编写类的功能描述
 *
 * @author fangwenhao
 * @created 2018/3/17
 */
@Component
public class MeetRoomOrderTask {

    @Autowired
    private MeetingroomOrderRepository meetingroomOrderRepository;

    /**
     * 定时修改会议状态 会议 -1 全部 1 未开始 2 已结束 3 进行中
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    public void refreshMeetingroomOrderStatus() {
        String dayStr = new DateTime().minusDays(1).toString("yyyy-MM-dd");
        List<MeetingroomOrder> meetingroomOrderList = meetingroomOrderRepository
                .findByStatusInAndAndPayStatusNotAndDayGreaterThanEqual(Lists.newArrayList(1, 3), 0,
                        DateUtil.string2Date(dayStr, "yyyy-MM-dd"));
        for (MeetingroomOrder meetingroomOrder : meetingroomOrderList) {
            String rangeList = meetingroomOrder.getRangeList();
            List<BookTimeRange> bookTimeRanges = JSONArray.parseArray(rangeList, BookTimeRange.class);
            if (!CollectionUtils.isEmpty(bookTimeRanges)) {
                String start = new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " "
                        + bookTimeRanges.get(0).getTime() + ":00";
                String endItem = new DateTime(meetingroomOrder.getDay()).toString("yyyy-MM-dd") + " "
                        + bookTimeRanges.get(bookTimeRanges.size() - 1).getTime() + ":00";
                Date startTime = DateUtil.string2Date(start, "yyyy-MM-dd HH:mm:ss");
                Date endTime = new DateTime(DateUtil.string2Date(endItem, "yyyy-MM-dd HH:mm:ss")).plusMinutes(30).toDate();
                if (new Date().before(startTime)) {
                    meetingroomOrder.setStatus(isAvaliable()?1:-3);
                } else if (new Date().after(endTime)) {
                    meetingroomOrder.setStatus(isAvaliable()?2:-3);
                } else {
                    meetingroomOrder.setStatus(isAvaliable()?3:-3);
                }
                meetingroomOrderRepository.save(meetingroomOrder);
            }
        }
    }

}
